package cn.itsource.org.controller;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/department")
@RestController
public class DepartmentController {

    @Autowired
    IDepartmentService departmentService;

    /**
     * 分页查询
     * @param query
     * @return
     */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        System.out.println(query.getCurrentPage());
        return departmentService.queryPage(query);
    }

    /**
     * 新增&修改
     * @param department
     * @return
     */
    @PutMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.add(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除方法")
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门删除",value = "department:delete")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/queryAll")
    public List<Department> queryAll(){
        return departmentService.queryAll();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }

    @GetMapping("/pid/{id}")
    public List<Department> queryByParentId(@PathVariable("id") Long id){
        return departmentService.queryByParentId(id);
    }

    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }
}
